package com.example.springboot.config.repeatbody;

import cn.hutool.core.io.IoUtil;
import lombok.SneakyThrows;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @Author:ChenZhangKun
 * @Date: 2024/3/19 21:03
 */
public class CacheRequestBodyContent extends HttpServletRequestWrapper {
    private byte[] body = null;

    public CacheRequestBodyContent(HttpServletRequest request) {
        super(request);
    }

    public CacheRequestBodyContent(HttpServletRequest request, ServletResponse response) {
        super(request);
        try {
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            // 读取后不关闭流
            body = IoUtil.readBytes(request.getInputStream(), false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream cache = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @SneakyThrows
            @Override
            public boolean isFinished() {
                return this.available() == 0;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return cache.read();
            }
        };
    }
}
